/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.deployment.dao;

import br.com.deployment.daogenerico.DaoGenerico;
import br.com.deployment.entidade.registroimovel.Averbacao;
import br.com.deployment.entidade.registroimovel.Imovel;
import br.com.deployment.exception.CartorioException;
import br.com.deployment.interfaces.AverbacaoDaoIn;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.Query;

/**
 *
 * @author luciano
 */
@LocalBean
@Stateless
public class AverbacaoDao extends DaoGenerico<Averbacao> implements AverbacaoDaoIn{
    
    public AverbacaoDao(){
        super(Averbacao.class);
    }
    
    @Override
    public List<Averbacao> findAverbacao(Averbacao averbacao) {
        return null;
    }
    
    @Override
    public Boolean exist(int id) throws CartorioException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    @Override
    public Averbacao findUltima(Imovel imovel) {
        String sql = "";
        Averbacao av = new Averbacao();
        if (imovel != null) {
            sql = "Select a from Imovel i JOIN i.averbacao a where "
                    + "i.id = :imo and "
                    + " a.id = "
                    + " (Select MAX(av.id) from Averbacao av where av.id = ANY"
                    + " (Select aver.id from Imovel im JOIN im.averbacao aver where "
                    + " im.id = i.id))";
        }
        
        Query query = getEm().createQuery(sql);
        if (imovel != null) {
            query.setParameter("imo", imovel.getId());
        }
        try{
            av = (Averbacao) query.getSingleResult();
        }catch(Exception e){
                return null;
        }
        return av;
    }
    
    @Override
    public List<Averbacao> findAverImovel(Imovel imovel, String order) {
        List<Averbacao> lstaverbacao = new ArrayList<Averbacao>();
        String sql = "";
        if (imovel != null) {
            sql = "Select a from Imovel i JOIN i.averbacao a where "
                    + " i.id = :imovel "
                    + " order by a.id "+ order.toUpperCase();
            Query query = getEm().createQuery(sql);
            query.setParameter("imovel", imovel.getId());
            
            try{
                lstaverbacao = query.getResultList();
            }catch(Exception e){
                return null;
            }
            
            System.err.println(lstaverbacao);
        }
        return lstaverbacao;
    }
}
